package com.lagou.sqlSession;

import com.lagou.config.BoundSql;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {
    // 生成已经设置好参数，可以直接执行sql语句的preparedStatement对象
    private PreparedStatement getPreparedStatementReady2Execute(Configuration configuration, MappedStatement mappedStatement, Object...params) throws Exception {
        // 1.注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();

        // 2.获取sql语句: select * from user where id = ${id} and username = #{username}
        // 转换sql语句：select * from user where id = ? and username = ?
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        // 3.获取预处理对象PreparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlTest());

        // 4.设置参数
        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterTypeClass = getClassType(parameterType);

        // 按id删除时参数只有一个id，且是Integer类型，不需要使用反射从中获取属性
        if (params != null && params.length == 1 && parameterTypeClass == Integer.class) {
            preparedStatement.setObject(1, params[0]);
            return preparedStatement;
        }

        // 原始sql语句中解析出来的参数名称集合
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            // 参数名称
            String content = parameterMapping.getContent();

            // 反射，从参数对象获取指定字段的名称，然后通过PreparedStatement设置参数
            Field declaredField = parameterTypeClass.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object paramVal = declaredField.get(params[0]);
            preparedStatement.setObject(i + 1, paramVal);
        }

        return preparedStatement;
    }

    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        PreparedStatement preparedStatement = getPreparedStatementReady2Execute(configuration, mappedStatement, params);

        // 5.执行sql
        ResultSet resultSet = preparedStatement.executeQuery();

        // 6.封装返回结果集
        String resultType = mappedStatement.getResultType();
        List<Object> objects = new ArrayList<>();
        while (resultSet.next()) {
            Class<?> resultTypeClass = getClassType(resultType);
            Object o = resultTypeClass.newInstance();
            // 获取元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            // 列下标从1开始
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 字段名
                String columnName = metaData.getColumnName(i);
                // 字段值
                Object columnValue = resultSet.getObject(i);
                // 使用反射或内省，根据库表和实体对应关系，完成数据封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, columnValue);
            }
            objects.add(o);
        }

        return (List<E>)objects;
    }

    @Override
    public int update(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        PreparedStatement preparedStatement = getPreparedStatementReady2Execute(configuration, mappedStatement, params);
        return preparedStatement.executeUpdate();
    }

    private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
        if (parameterType == null) {
            return null;
        }
        return Class.forName(parameterType);
    }

    /**
     * 完成对#{}的解析工作：1.将#{}使用?占位符进行代替 2.解析出#{}里面的值进行存储
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        // 标记处理类，配合标记解析器来完成对占位符的标记处理工作
        ParameterMappingTokenHandler tokenHandler = new ParameterMappingTokenHandler();
        // 标记解析器
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", tokenHandler);
        // 解析出来的sql语句
        String parseSql = genericTokenParser.parse(sql);
        // #{}里面解析出来的参数名称
        List<ParameterMapping> parameterMappings = tokenHandler.getParameterMappings();
        return new BoundSql(parseSql, parameterMappings);
    }
}
